package com.jiusit.onePurchase.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jiusit.common.utils.StringUtil;
import com.jiusit.onePurchase.interceptor.UserInterceptor;
import com.jiusit.onePurchase.model.PurchaseAdvertisement;
import com.jiusit.onePurchase.model.PurchaseCommodity;
import com.jiusit.onePurchase.model.PurchaseCommodityBuy;
import com.jiusit.onePurchase.model.PurchaseCommodityCar;
import com.jiusit.onePurchase.model.PurchaseCommodityCollect;
import com.jiusit.onePurchase.model.PurchaseCommodityContent;
import com.jiusit.onePurchase.model.PurchaseCommodityRecord;
import com.jiusit.onePurchase.model.PurchaseCommodityVersion;
import com.jiusit.onePurchase.model.PurchaseSentAddress;
import com.jiusit.onePurchase.model.PurchaseVersionExt;
import com.jiusit.onePurchase.model.OnePurchaseUser;
import com.jiusit.onePurchase.model.PurchaseCommodityPay;
@ControllerBind(controllerKey="/home",viewPath="/pages")
@Before(UserInterceptor.class)


/*
 * 首页
 * */
public class HomeController extends ApiController{
	private static final Logger log = Logger
			.getLogger(HomeController.class);

	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
   //首页
	
	public void homePage(){
		String from_user=getCookie("from_user9");
		/*if(StringUtil.isEmpty(from_user)){
			from_user=getPara("from_user");
		}
		System.out.println(from_user);
		setAttr("from_user",from_user);*/
		if(!StringUtil.isEmpty(from_user)){
		OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
		System.out.println(user.getInt("login_num"));
		List <PurchaseAdvertisement> topAdvertisementList=PurchaseAdvertisement.dao.find("select * from purchase_advertisement where top_show='1' and is_enable='1' order by sort ");
		PurchaseAdvertisement advertisement=PurchaseAdvertisement.dao.findFirst("select * from purchase_advertisement where top_show='0' and is_enable='1' order by sort");
		Page <PurchaseCommodity> commodityPage=PurchaseCommodity.dao.paginate(1,10,"select * "," from purchase_commodity where commodity_type='01' and commodity_status='01' order by sort");
		Page <PurchaseCommodity> purchasePage=PurchaseCommodity.dao.paginate(1,10,"select b.commodity_name,b.commodity_logo,a.total_count,a.surplus_count,a.commodity_id,a.id,(a.total_count-a.surplus_count)*100/a.total_count as 'per' ","from purchase_time_slot a left join purchase_commodity b on b.id=a.commodity_id  where b.commodity_type='02' and b.commodity_status='01' and a.is_over='0' and status ='01' and NOW() BETWEEN a.begin_date and a.end_date  order by a.sort, a.surplus_count ");
		setAttr("topAdvertisementList", topAdvertisementList);
		setAttr("advertisement", advertisement);
		setAttr("commodityList", commodityPage.getList());
		setAttr("commodityTotalPage", commodityPage.getTotalPage());
		setAttr("commodityPageNumber", commodityPage.getPageNumber());
		setAttr("purchaseList", purchasePage.getList());
		setAttr("purchaseTotalPage", purchasePage.getTotalPage());
		setAttr("purchasePageNumber", purchasePage.getPageNumber());
		setAttr("login_num", user.getInt("login_num"));
		setAttr("server_uri", PropKit.get("server_uri"));
		render("index.html");
		}else{
			System.out.println(getRequest().getRequestURI());
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("home")-1, url.length()));
			render("error.html");
		}
	}
	//普通商品分页
	@Clear
   public void commodityListPage(){
		String from_user=getCookie("from_user9");
		if(StringUtil.isEmpty(from_user)){
			from_user=getPara("from_user");
		}
	   setAttr("from_user",from_user);
	   String page=getPara("page");
	   if(StringUtil.isEmpty(page)){
		   page="1";
	   }
		Page <PurchaseCommodity> commodityPage=PurchaseCommodity.dao.paginate(Integer.parseInt(page),10,"select * ","from purchase_commodity where commodity_type='01' and commodity_status='01' order by sort");
		setAttr("commodityPage", commodityPage);
		setAttr("server_uri", PropKit.get("server_uri"));
		renderJson(commodityPage);
	}
   //普通商品明细
	
   public void commodityDetail(){
		String id=getPara("id"); //商品id
		String from_user=getCookie("from_user9");
		if(!StringUtil.isEmpty(from_user)){
		OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
		PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
		Map map=new HashMap();
		setAttr("count", commodityCollect.getLong("count"));
		PurchaseCommodity commodity=PurchaseCommodity.dao.findById(id);
		List<PurchaseCommodityVersion> commodityVersionList=PurchaseCommodityVersion.dao.find("select * from purchase_commodity_version where commodity_id='"+id+"' and version_stock > 0 order by version_sort ");
		List<PurchaseVersionExt> versionExtList = new ArrayList<PurchaseVersionExt>();
		if(commodityVersionList.size()>0){
		   versionExtList=PurchaseVersionExt.dao.find("select * from purchase_version_ext where version_id='"+commodityVersionList.get(0).get("id")+"' order by ext_sort");
		   setAttr("version_stock", commodityVersionList.get(0).get("version_stock"));
		}
		Page<PurchaseCommodityContent> commodityContent=PurchaseCommodityContent.dao.paginate(1, 10, "select a.*", " from purchase_commodity_content a  where a.commodity_id='"+id+"'");
		List<PurchaseCommodityContent> commodityContentList=PurchaseCommodityContent.dao.find( "select a.* from purchase_commodity_content a  where a.commodity_id='"+id+"'");
		List<PurchaseCommodityCar> commodityCarlist = PurchaseCommodityCar.dao.find("select * from purchase_commodity_car where user_id = '"+user.getStr("id")+"' and order_type='01' and commodity_type = '01' order by create_date desc ");
		setAttr("commodity", commodity);
		setAttr("commodityVersionList", commodityVersionList);
		setAttr("commodityContentList", commodityContent.getList());
		setAttr("commodityContentTotalPage", commodityContent.getTotalPage());
		setAttr("commodityContentPageNumber", commodityContent.getPageNumber());
		setAttr("total_num", commodityContentList.size());
		setAttr("versionExtList", versionExtList);
		setAttr("car_size", commodityCarlist.size());
		setAttr("server_uri", PropKit.get("server_uri"));
		render("product_detail.html");
		}else{
			System.out.println(getRequest().getRequestURI());
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("home")-1, url.length())+"?id="+id);
			render("error.html");
		}
		
	}
   
   //型号轮播图片切换
	@Clear
   public void changeVersionPic(){
		String id=getPara("id");
		String from_user=getCookie("from_user9");
		if(StringUtil.isEmpty(from_user)){
			from_user=getPara("from_user");
		}
	   setAttr("from_user",from_user);
		String version_id=getPara("version_id");
		List<PurchaseVersionExt> versionExtList=PurchaseVersionExt.dao.find("select * from purchase_version_ext where version_id='"+version_id+"' order by ext_sort");
		Map map=new HashMap();
		map.put("versionExtList", versionExtList);
		map.put("server_uri", PropKit.get("server_uri"));
		renderJson(map);
	}
   //一元购商品分页
	@Clear
   public void onePurchaseListPage(){
		String from_user=getCookie("from_user9");
		if(StringUtil.isEmpty(from_user)){
			from_user=getPara("from_user");
		}
	   setAttr("from_user",from_user);
	   String page=getPara("page");
	   if(StringUtil.isEmpty(page)){
		   page="1";
	   }

		Page <PurchaseCommodity> purchasePage=PurchaseCommodity.dao.paginate(Integer.parseInt(page),10,"select b.commodity_name,b.commodity_logo,a.total_count,a.surplus_count,a.commodity_id,a.id,(a.total_count-a.surplus_count)*100/a.total_count as 'per' ","from purchase_time_slot a left join purchase_commodity b on b.id=a.commodity_id  where b.commodity_type='02' and b.commodity_status='01' and a.is_over='0' and status ='01' and NOW() BETWEEN a.begin_date and a.end_date  order by a.sort, a.surplus_count ");
		setAttr("purchasePage", purchasePage);
		setAttr("server_uri", PropKit.get("server_uri"));
		renderJson(purchasePage);
	}
		 //是否收藏
	    @Clear
		public void isCollect(){
	    	String from_user=getCookie("from_user9");
			if(StringUtil.isEmpty(from_user)){
				from_user=getPara("from_user");
			}
		   setAttr("from_user",from_user);
			String id = getPara("id");
			OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
			PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
			Map map=new HashMap();
			map.put("count", commodityCollect.getLong("count"));
			renderJson(map);
		}
		
		 //收藏
		public void collectCommodity(){
			String from_user=getCookie("from_user9");
			if(StringUtil.isEmpty(from_user)){
				from_user=getPara("from_user");
			}
		   setAttr("from_user",from_user);
			String id = getPara("id"); //商品id
			String commodity_type = getPara("commodity_type"); //商品类型
			OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
			PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select id, count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
			Map map=new HashMap();
			if(commodityCollect.getLong("count") >0){
				PurchaseCommodityCollect.dao.deleteById(commodityCollect.get("id"));
				map.put("code", "1");
				map.put("msg", "成功取消收藏");
				
			}else{
				PurchaseCommodityCollect collect=new PurchaseCommodityCollect().set("id", StringUtil.getUUID())
						.set("commodity_id", id)
						.set("user_id", user.get("id"))
						.set("collect_date", new Date())
						.set("commodity_type", commodity_type)
						.set("create_by", user.get("id"))
						.set("create_name", user.get("nick_name"))
						.set("create_date", new Date())
						.set("update_by", user.get("id"))
						.set("update_name", user.get("nick_name"))
						.set("update_date", new Date())
						.set("remarks","收藏商品")
						;
				collect.save();
				map.put("code", "0");
				map.put("msg", "收藏成功");
			}
			
			renderJson(map);
		}
		
		//浏览
				public void browseCommodity(){
					String id=getPara("id");
					String from_user=getCookie("from_user9");
					if(StringUtil.isEmpty(from_user)){
						from_user=getPara("from_user");
					}
				    setAttr("from_user",from_user);
					String commodity_type=getPara("commodity_type");
					OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
					PurchaseCommodityRecord countRecord=PurchaseCommodityRecord.dao.findFirst("select count(*) as 'count' from purchase_commodity_record where user_id='"+user.get("id")+"'");
					
					PurchaseCommodityRecord checkRecord=PurchaseCommodityRecord.dao.findFirst("select * from purchase_commodity_record where user_id='"+user.get("id")+"' and commodity_id='"+id+"'");
					if(checkRecord == null){
						if(countRecord.getLong("count") < 20){
					PurchaseCommodityRecord commodityRecord=new PurchaseCommodityRecord().set("id", StringUtil.getUUID())
							.set("commodity_id", id)
							.set("user_id", user.get("id"))
							.set("record_date", new Date())
							.set("commodity_type", commodity_type)
							.set("create_by", user.get("id"))
							.set("create_name", user.get("nick_name"))
							.set("create_date", new Date())
							.set("update_by", user.get("id"))
							.set("update_name", user.get("nick_name"))
							.set("update_date", new Date())
							.set("remarks", "商品浏览记录")
							;
					commodityRecord.save();
						}
					}else{
						PurchaseCommodityRecord updateRecord=new PurchaseCommodityRecord().set("id", checkRecord.get("id"))
								.set("record_date", new Date())
								;
						updateRecord.update();
					}
					renderNull();
				}
				
				//评论分页
				@Clear
			   public void commodityContentPage(){
				   String page=getPara("page");
				   String commodity_id=getPara("commodity_id");
				   if(StringUtil.isEmpty(page)){
					   page="1";
				   }
				   Page<PurchaseCommodityContent> commodityContent=PurchaseCommodityContent.dao.paginate(Integer.parseInt(page), 10, "select a.*", " from purchase_commodity_content a  where a.commodity_id='"+commodity_id+"'");
				   setAttr("commodityPage", commodityContent);
					setAttr("server_uri", PropKit.get("server_uri"));
					renderJson(commodityContent);
				}
				//一元购介绍页
				@Clear
			   public void introduceOnePurchase(){
				   
				   render("rule.html");
				}
}
